<?php


namespace broadcast\middleware;

use app\Request;
use broadcast\exceptions\AuthException;
use broadcast\interfaces\MiddlewareInterface;
use broadcast\redis\setRedis;
use think\facade\Config;
/**
 * token验证
 * Class AuthWebMiddleware
 * @package learn\middleware
 */
class AuthWebMiddleware implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @param bool $force
     * @return mixed
     */
    public function handle(Request $request, \Closure $next, bool $force = true)
    {
        $website = null;
        $token = trim(ltrim($request->header('Authori-website'), 'Bearer'));
        if(!$token)  $token = trim(ltrim($request->header('Authoriwebsite'), 'Bearer'));
        // if(!$token)  $token = trim(ltrim($_GET['key'], 'Bearer'));
        try {
            $website = lockcode($token);
            if($website == '') return app('json')->make('2001', '未获取网站配置');
            dynamicSetMysql($website);
            $redisInfo = setRedis::getCache($website,"redis");
            if (!$redisInfo) {
                $redis = file_get_contents("https://live.tanjfst.com/redisfile/".$website.".json");
                setRedis::setCache(session("website"),"redis",$redis);
                $redisInfo = json_decode($redis,true);
            }
            editRedisConfig($redisInfo);
            
        } catch (AuthException $e) {
            if ($force)
                return app('json')->make('2001', '网站配置过期');
        }
        Request::macro('isWebLogin', function () use (&$website) {
            return !is_null($website);
        });
        Request::macro('website', function () use (&$website) {
            return is_null($website) ? 0 : $website;
        });
        return $next($request);
    }
}